/*
 * Copyright (C) 2014 Lucas Rocha
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.meij.adapter;

import java.util.ArrayList;

import org.lucasr.twowayview.widget.SpannableGridLayoutManager;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.meij.R;
import com.meij.bean.Avatar;
import com.meij.http.Url;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
	private final Context context;
	private ArrayList<Avatar> avatars = new ArrayList<Avatar>();

	public static class ViewHolder extends RecyclerView.ViewHolder {
		public final TextView textView1;
		public final TextView textView2;
		public final ImageView imageView1;

		public ViewHolder(View view) {
			super(view);
			textView1 = (TextView) view.findViewById(R.id.textView1);
			textView2 = (TextView) view.findViewById(R.id.textView2);
			imageView1 = (ImageView) view.findViewById(R.id.imageView1);
		}
	}

	public MainAdapter(Context context, ArrayList<Avatar> avatars) {
		this.context = context;
		this.avatars = avatars;
	}

	@Override
	public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		final View view = LayoutInflater.from(context).inflate(R.layout.item_main, parent, false);
		return new ViewHolder(view);
	}

	@Override
	public void onBindViewHolder(ViewHolder holder, int position) {
		View itemView = holder.itemView;
		Avatar avatar = avatars.get(position);
		SpannableGridLayoutManager.LayoutParams lp = (SpannableGridLayoutManager.LayoutParams) itemView.getLayoutParams();
		AQuery aq = new AQuery(itemView);
		aq.id(holder.textView1).text(avatar.getDistance() + "m");
		aq.id(holder.textView2).text(avatar.getNickname());
		aq.id(holder.imageView1).image(Url.ctx + avatar.getAvatar());
		switch (position) {
		case 0:
			lp.colSpan = 2;
			lp.rowSpan = 2;
			break;
		default:
			lp.colSpan = 1;
			lp.rowSpan = 1;
			break;
		}
		itemView.setLayoutParams(lp);
	}

	@Override
	public int getItemCount() {
		return avatars == null ? 0 : avatars.size();
	}
}
